package com.goldcn.user.service;

import com.goldcn.common.consts.RestConst;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.util.IdGen;
import com.goldcn.interceptor.SystemContext;
import com.goldcn.user.dao.CompanyInfoMapper;
import com.goldcn.user.dao.OrganizationalMapper;
import com.goldcn.user.dao.UserInfoMapper;
import com.goldcn.user.dao.UserLoginMapper;
import com.goldcn.user.dto.RegisterDto;
import com.goldcn.user.model.*;
import com.google.common.base.Objects;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.List;


/**
 * Created by 1111 on 2016/11/8.
 */
@Service
@Transactional
@ConfigurationProperties(prefix = "sms")
public class UserLoginService {
    private String mobileZoneResult;

    @Autowired
    UserLoginMapper userLoginMapper;

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    OrganizationalService organizationalService;

    @Autowired
    OrganizationalMapper organizationalMapper;

    @Autowired
    RestTemplate rest;

    @Autowired
    CompanyInfoMapper companyInfoMapper;

    public void setMobileZoneResult(String mobileZoneResult) {
        this.mobileZoneResult = mobileZoneResult;
    }

    public int insertUserLogin(UserLogin userLogin) {
        userLogin.setId(IdGen.get().nextId());
        return userLoginMapper.insert(userLogin);
    }

    public int deleteUserLogin(Long userID) {

        List<UserLogin> userLogins = userLoginMapper.selectByUserID(userID);
        for (UserLogin userLogin : userLogins) {
            String account = userLogin.getLoginName();
            List<UserInfo> userInfos = userInfoMapper.getUserByAccount(account, null, SystemContext.getCompanyID());
            if (CollectionUtils.isEmpty(userInfos)) {
                userLoginMapper.deleteByPrimaryKey(userLogin.getId());
            }
        }

        return userLoginMapper.deleteByPrimaryKey(userID);
    }

    public int updateUserLogin(UserLogin userLogin) {
        return userLoginMapper.updateByPrimaryKeySelective(userLogin);
    }

    //登录验证用户名密码
    public UserLogin selectForLogin(UserLogin userLogin) {
        userLogin.setCompanyID(SystemContext.getCompanyID());
        return userLoginMapper.selectForLogin(userLogin);
    }

    //验证登录名、手机号是否存在
    public int selectLoginName(String loginName) {
//        List<UserInfo> ui1s = new ArrayList<>();
//                ui1s = userInfoMapper.selectByPhone(loginName);
//        UserInfo ui2 = userInfoMapper.selectByAccount(loginName);
        String companyID = SystemContext.getRequest().getHeader("companyID");
        System.out.println("get companyID  =  " + companyID);
        UserLogin userLogin = userLoginMapper.selectLoginName(loginName, SystemContext.getCompanyID());
        if (userLogin == null) {
            return 1; //不存在则返回0
        } else {
            return 0;  //已存在则返回1
        }
    }


    //验证登录名、手机号是否存在
    public int selectLoginName2(String loginName, Integer type) {
        List<UserInfo> userInfos = userInfoMapper.getUserByAccount(loginName, type, SystemContext.getCompanyID());
        if (CollectionUtils.isEmpty(userInfos)) {
            /*UserLogin userLogin = userLoginMapper.selectLoginName(loginName,SystemContext.getCompanyID());
            if(userLogin == null){
                return 1;//不存在
            }else{
                return 2;
            }*/
            return 1;//不存在
        }

        /*UserInfo userInfo = userInfos.get(0);
        CompanyInfo companyInfo = companyInfoMapper.selectByUserID(userInfo.getUserID());
        if(companyInfo == null){
            return 1;//不存在
        }*/
        return 0;//已存在
    }

    //loginName查询userLogin信息
    public UserLogin selectByLoginName(String loginName) {
        return userLoginMapper.selectLoginName(loginName, SystemContext.getCompanyID());
    }

    //保存注册信息 调用保存userInfo以及userLogin的信息
    public Object register(RegisterDto registerDto) throws Exception {
        UserInfo userInfo = new UserInfo();
        userInfo.setAccount(registerDto.getLoginName());
        userInfo.setMobile(registerDto.getLoginName());
        userInfo.setPassWord(registerDto.getPassWord());
        userInfo.setType(registerDto.getType());
        if (registerDto.getType() == 4) { //会员注册需要查询推荐人信息
            /**
             //如果推荐人为空则找到手机号归属地对应的分行
             if(registerDto.getRecommenderPhone() == null || registerDto.getRecommenderPhone()==0){
             String zoneResult = getMobileZoneResult(registerDto.getLoginName()).toString();  //获取归属地
             Long oID = organizationalMapper.selectIDByName(zoneResult);  //获取归属地分行的ID
             if(oID!=null){
             userInfo.setOrganizationalID(oID);
             }else {
             Organizational organizational = organizationalService.selectHeadCCB();
             userInfo.setOrganizationalID(organizational.getoID());
             }
             userInfo.setPaterID(Long.parseLong("0"));
             */
            //如果不填推荐码则会员归属于总行直属会员
            if (registerDto.getRecommenderPhone() == null || registerDto.getRecommenderPhone() == 0) {
                Organizational organizational = organizationalService.selectHeadCCB(SystemContext.getCompanyID());
                userInfo.setOrganizationalID(organizational.getoID());
                userInfo.setPaterID(Long.parseLong("0"));
            } else {
                UserInfo userRecommender = userInfoService.selectByRecommendNO(registerDto.getRecommenderPhone());
                if (userRecommender == null) {
                    throw new ServiceException("推荐码不存在", RestConst.ErrorCode.FORM_FAIL);
                }

                userInfo.setOrganizationalID(userRecommender.getOrganizationalID());
                userInfo.setPaterID(userRecommender.getUserID());  //获取推荐人的userID

                //增加所属店铺ID added by pengzh 2018-3-18
                userInfo.setShopID(getShopIDByUserID(userRecommender.getUserID()));
            }
        }
        return userInfoService.addUserInfo(userInfo);
    }

    //根据用户查找shopID，员工可能userInfo表shopID为空情况
    public Long getShopIDByUserID(Long userID) {
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userID);
        Long shopID = userInfo.getShopID();
        if (shopID == null || Objects.equal(shopID, 0l)) {
            CompanyInfo companyInfo = companyInfoMapper.getMallInfo(userInfo.getOrganizationalID());
            shopID = companyInfo.getCompanyInfoID();
        }
        System.out.print("=====shopID===" + shopID);
        return shopID;

    }

    //获取号码归属地
    private Object getMobileZoneResult(String mobile) {
        try {
            String strData = rest.getForObject(mobileZoneResult + mobile, String.class);
            String str = strData.split("=")[1];
            JSONObject jsonObject = JSONObject.fromObject(str);
            return jsonObject.get("province").toString();
        } catch (Exception e) {
            System.out.print(e);
            throw new ServiceException("调用淘宝手机号归属地查询失败");
        }
    }




}
